#include <func.h>

int main(int argc,char **argv)
{
    //传入参数： ip地址，端口号
    ARGS_CHECK(argc,3);

    //初始化socket，带有一个缓冲区
    int socketFd = socket(AF_INET,SOCK_STREAM,0);//AF_INET代表ipv4 SOCK_STREAM代表流式socket，
                                                //用于tcp协议，0表示i
    ERROR_CHECK(socketFd,-1,"socket");

    printf("server: socketFd:%d\n",socketFd);

    struct sockaddr_in sockad;
    bzero(&sockad,sizeof(sockad));
    sockad.sin_family = AF_INET;
    sockad.sin_addr.s_addr = inet_addr(argv[1]);//inet_addr:把点分10进制的ip转换成in_addr_t(32位unsinged int)
    sockad.sin_port = htons(atoi(argv[2]));//htons 处理16位 转换成网络字节序
    
    int ret = bind(socketFd,(struct sockaddr*)&sockad,sizeof(sockad));
    ERROR_CHECK(ret,-1,"bind");

    printf("server: bind done, listening...\n");
    listen(socketFd,10);//第二个参数是backlog 代表同时能处理的最大连接要求，通常10or5 最大128

    int newFd;
    struct sockaddr_in client;
    bzero(&client,sizeof(client));
    socklen_t len = sizeof(client);
    newFd = accept(socketFd,(struct sockaddr*)&client,&len);
    printf("server: accept! conneted. waiting for client...\n");


    ERROR_CHECK(newFd,-1,"accept");
    char str[128] = {0};
    recv(newFd,str,sizeof(str),0);
    printf("server: received: %s\n",str); 
    printf("input your words to client:\n");
    read(STDIN_FILENO,str,sizeof(str));
    send(newFd,str,strlen(str)-1,0);
    
    return 0;
}

